#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include "SDL/SDL.h"
#include "guacimage.h"

int video_open(lua_State *L)
{
    unsigned int flags = 0;
    if (lua_toboolean(L,3))
        flags |= SDL_FULLSCREEN;
    SDL_SetVideoMode(luaL_checkint(L,1), luaL_checkint(L,2), 32, flags);
    GuacImage* screenImage = (GuacImage*)lua_newuserdata(L, sizeof(GuacImage));
    screenImage->surf = SDL_GetVideoSurface();
    screenImage->prect = NULL;
    screenImage->flags = 0;
    screenImage->handle_x = screenImage->handle_y = 0;
    lua_getfield(L, LUA_REGISTRYINDEX, "image meta");
    lua_setmetatable(L,-2);
    return 1;
}

int video_flip(lua_State* L)
{
    SDL_Flip(SDL_GetVideoSurface());
    return 0;
}

int video_clear(lua_State* L)
{
    SDL_Surface* surf = SDL_GetVideoSurface();
    SDL_SetClipRect(surf, NULL);
    SDL_FillRect(surf, NULL, 0x000000);
    return 0;
}

luaL_Reg video_functions[] = {
    {"open",video_open},
    {"flip",video_flip},
    {"clear",video_clear},
    {NULL,NULL}
};

int luaopen_video(lua_State* L)
{
    if (!SDL_WasInit(SDL_INIT_VIDEO))
        SDL_InitSubSystem(SDL_INIT_VIDEO);

    lua_getglobal(L, "require");
    lua_pushliteral(L, "image");
    lua_call(L,1,0);

    luaL_register(L, "video", video_functions);

    return 1;
}
